package com.atguigu.cf.test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * author: 封捷
 * date: 2023/1/29 16:56
 * version: 1.0
 */
public class Demo07TaskAllOf {

    public static void main(String[] args) {

        ExecutorService threadPool = ThreadPoolProvider.getThreadPool();

        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("任务01完成。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task 01 result";
        }, threadPool);
        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(4);
                System.out.println("任务02完成。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task 02 result";
        }, threadPool);
        CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(6);
                System.out.println("任务03完成。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task 03 result";
        }, threadPool);

        // 被汇总任务都完成，触发 futureAllOf 的完成事件
        CompletableFuture<Void> futureAllOf = CompletableFuture.allOf(future01, future02, future03);

        futureAllOf.whenComplete((taskResult, throwable) -> {
            System.out.println("allOf 任务的完成事件被触发。");
        });


    }

}
